package com.cotte.flow.kafka;

import org.apache.avro.generic.GenericRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.ProducerListener;
import org.springframework.stereotype.Component;

@Component
public class Producer {
	
	protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private KafkaTemplate kafkaTemplate;
    
    public void send(String topic , String message) {
    	logger.info("向kafka推送数据:[{}]", message);
    	try {
    		kafkaTemplate.send(topic, message);
            logger.info("发送kafka成功.");
    	}catch(Exception e) {
    		logger.error("发送数据出错！！！{}{}", topic, message);
    		logger.error("发送数据出错=====>", e);
    	}
    	//消息发送的监听器，用于回调返回信
    	kafkaTemplate.setProducerListener(new ProducerListener<String, String>() {

			@Override
			public boolean isInterestedInSuccess() {
				logger.info("数据发送完毕");
				return false;
			}

			@Override
			public void onError(String arg0, Integer arg1, String arg2, String arg3, Exception arg4) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onSuccess(String arg0, Integer arg1, String arg2, String arg3, RecordMetadata arg4) {
				// TODO Auto-generated method stub
				
			}
		});
    }
}
